package cn.news.upload.service;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import cn.news.upload.dao.XhUploadAppDao;
import cn.news.upload.dao.XhUploadInfoDao;
import cn.news.upload.entities.OperResult;
import cn.news.upload.entities.XhUploadApp;
import cn.news.upload.entities.XhUploadInfo;

@Service
public class InfoService {
	private static final Logger logger = LoggerFactory.getLogger(InfoService.class);

	@Autowired
	private XhUploadInfoDao infodao;

	@Autowired
	private XhUploadAppDao appdao;

	public void addInfo(XhUploadInfo info) {
		XhUploadInfo ifu = infodao.saveAndFlush(info);
		info.setId(ifu.getId());
	}
	
	public Page<XhUploadInfo> getInfoList(final XhUploadInfo info, Pageable pageable) {
		Page<XhUploadInfo> rs = infodao.findAll(new Specification<XhUploadInfo>() {
			List<Predicate> predicates = new ArrayList<>();

			@Override
			public Predicate toPredicate(Root<XhUploadInfo> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				if (info.getAppId() > 0) {
					predicates.add(cb.equal(root.get("appId"), info.getAppId()));
				}
				if (null != info.getType()) {
					predicates.add(cb.equal(root.get("type"), info.getType()));
				}
				if (info.getIsPass() > -1) {
					predicates.add(cb.equal(root.get("isPass"), info.getIsPass()));
				}
				if (null != info.getTag()) {
					predicates.add(cb.equal(root.get("tag"), info.getTag()));
				}
				return cb.and(predicates.toArray(new Predicate[predicates.size()]));
			}
		}, pageable);
		return rs;
	}

	public OperResult checkApp(XhUploadInfo info, String referer) {
		OperResult or = new OperResult();

		Long id = (long) info.getAppId();
		XhUploadApp app = appdao.findOne(id);

		if (null == app) {
			or.setCode(OperResult.CODE_FAIL);
			or.setMessage("App ID is not correct");
		}

		if (StringUtils.equals(app.getStatus(), "0")) {
			or.setCode(OperResult.CODE_FAIL);
			or.setMessage("App is colsed");
		}

		// if(!StringUtils.equals(app.getDescp(), referer)){
		// or.setCode(OperResult.CODE_FAIL);
		// or.setMessage("App ID is not correct");
		// }

		return or;
	}
}
